<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- <script src="./myPubSub.js"></script> -->
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
    <script src="./myPubSub.js"></script>
    <div id="root"></div>

    <script type="text/babel">
      // 实现兄弟组件传值 不通过父组件 使用发布订阅模式
      let root = document.getElementById("root");
      class X1 extends React.Component {
        state = {
          person: "",
        };

        givePerson = () => {
          PubSub.publish("givePerson", this.state.person);
        };
        handle = (e) => {
          this.setState({
            person: e.target.value,
          });
        };
        render() {
          return (
            <div className="x1">
              <input value={this.state.person} onChange={this.handle} />
              <button onClick={this.givePerson}>点击传值</button>
              <X2 />
            </div>
          );
        }
      }
      class X2 extends React.Component {
        render() {
          return <X3 />;
        }
      }
      class X3 extends React.Component {
        state = {
          persons: ["张三", "李四"],
        };
        componentDidMount() {
          PubSub.subscribe("givePerson", this.getPerson);
        }
        getPerson = (type, person) => {
          console.log(type, person);
          let { persons } = this.state;
          persons.push(person);
          this.setState({
            persons,
          });
        };
        render() {
          return (
            <ul>
              {this.state.persons.map((person, index) => (
                <li key={index}>{person}</li>
              ))}
            </ul>
          );
        }
      }
      class App extends React.Component {
        render() {
          return (
            <div>
              <X1 />
            </div>
          );
        }
      }
      ReactDOM.render(<App />, root);
    </script>
  </body>
</html>
